package com.kylin.common.security.domain;

import com.alibaba.fastjson2.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录用户身份权限
 *
 * @author wuhao
 * @version 1.0 - 2019-08-19
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LoginUser implements UserDetails {
    /**
     * 用户ID，必填
     */
    private Long userId;
    
    /** 用户名 */
    private String username;
    
    /** 密码 */
    private String password;

    /** 昵称 */
    private String nickName;

    /** 头像 */
    private String avatar;

    /** 手机号 */
    private String phone;

    /** openid */
    private String openid;
    
    /** 部门ID */
    private Long deptId;

    /** 权限集合 */
    private Set<String> permissions;

    /** 角色集合 */
    private Set<String> roles;
    
    /** 账号类型，区分不同用户对象,默认是系统后台用户 */
    private String accountType = "system";

    /** 启用 */
    private boolean enable = true;

    @JSONField(serialize = false)
    List<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities!=null){
            return authorities;
        }
        authorities = new ArrayList<>();
        // 权限
        if(permissions != null && permissions.size() > 0) {
            authorities.addAll(permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        }

        // 角色
        if(!Objects.isNull(roles) && roles.size() > 0) {
            authorities.addAll(roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        }
        return authorities;
    }

    public LoginUser(long userId, String username, String password) {
        this.userId = userId;
        this.username = username;
        this.password = password;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enable;
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }
}
